import { defineComponent, reactive, ref } from "vue";
import Popup from "@/components/Popup/Popup";
import styles from "./Add.module.less";
import to from "await-to-js";
import _ from "lodash";
import { message } from "ant-design-vue";
import { EyeInvisibleOutlined, EyeOutlined } from "@ant-design/icons-vue";
export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ["change"],
  setup(props, { emit, expose }) {
    const addPopupRef = ref(null as any);
    const formRef = ref(null as any);
    const state = reactive({
      type: "add",
      form: {
        userId: '',
        nickName: null,
        phonenumber: null,
        email: null,
        userName: null,
        password: null,
        sex: null,
        status: '0',
        roleIds: [],
        remark: null,
      },
      options: {
        sexs: [
          { label: '男', value: '0' },
          { label: '女', value: '1' },
          { label: '未知', value: '2' },
        ],
        roles: [] as any[],
      },
      showPassword: false,
    })
    const editing = ref(false);
    // 获取详情
    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.userId));
      if (!err) {
        const resultObj = res?.data?.data || {};
        state.form.nickName = resultObj?.nickName || null;
        state.form.phonenumber = resultObj?.phonenumber || null;
        state.form.email = resultObj?.email || null;
        state.form.userName = resultObj?.userName || null;
        if (state.type === 'add') {
          state.form.password = resultObj?.password || '123456';
        }
        state.form.sex = resultObj?.sex || null;
        state.form.status = resultObj?.status || "0";
        state.form.roleIds = res?.data?.roleIds || [];
        state.form.remark = resultObj?.remark || null;
        state.options.roles = res?.data?.roles || [];
      }
    }
    // 打开弹窗
    const open = async ({ type, userId }) => {
      state.type = type;
      state.form.userId = userId || '';
      await getDetail();
      addPopupRef.value.open();
    }
    const submit = async () => {
      formRef.value
        .validate()
        .then(async () => {
          editing.value = true;
          const params = _.cloneDeep(state.form);
          const [err, res]: any = await to((state.type === 'edit' ? props.service?.edit : props.service?.add)(params));
          if (!err) {
            message.success(state.type === 'edit' ? '编辑成功' : '添加成功');
            addPopupRef.value.close();
            emit('change');
          }
          editing.value = false;
        })
    }
    expose({
      open,
    })
    return () => (
      <Popup ref={addPopupRef}
        title={state.type === 'edit' ? "编辑用户" : "添加用户"}
        width="800px"
        oriState={state}
        v-slots={{
          footer: () => <>
            <a-button type="primary" loading={editing.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }}>取消</a-button>
          </>
        }}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
              <a-form-item required label="用户昵称" name="nickName">
                <a-input v-model:value={state.form.nickName} placeholder="请输入用户昵称" />
              </a-form-item>
              <a-form-item label="手机号码" name="phonenumber">
                <a-input v-model:value={state.form.phonenumber} placeholder="请输入手机号码" />
              </a-form-item>
              <a-form-item label="邮箱" name="email">
                <a-input v-model:value={state.form.email} placeholder="请输入邮箱" />
              </a-form-item>
              <a-form-item required label="用户名称" name="userName">
                <a-input v-model:value={state.form.userName} placeholder="请输入用户名称" />
              </a-form-item>
              {
                state.type === 'add' && (
                  <a-form-item required label="用户密码" name="password">
                    <a-input type={state.showPassword ? 'text' : 'password'} v-model:value={state.form.password} placeholder="请输入用户密码" v-slots={{
                      suffix: () => <div style={{ cursor: "pointer" }} onClick={() => { state.showPassword = !state.showPassword }}>{state.showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}</div>
                    }} />
                  </a-form-item>
                )
              }
              <a-form-item label="用户性别" name="sex">
                <a-select v-model:value={state.form.sex} placeholder="请选择用户性别">
                  {
                    state.options.sexs.map((item) => (
                      <a-select-option value={item.value}>{item.label}</a-select-option>
                    ))
                  }
                </a-select>
              </a-form-item>
              <a-form-item label="状态" name="status">
                <a-radio-group
                  v-model:value={state.form.status}
                  name="radioGroup"
                >
                  <a-radio value={"0"}>正常</a-radio>
                  <a-radio value={"1"}>停用</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="角色" name="roleIds">
                <a-select mode="multiple" v-model:value={state.form.roleIds} placeholder="请选择角色">
                  {
                    state.options.roles.map((item) => (
                      <a-select-option value={item.roleId}>{item.roleName}</a-select-option>
                    ))
                  }
                </a-select>
              </a-form-item>
              <a-form-item label="备注" name="remark">
                <a-textarea v-model:value={state.form.remark} />
              </a-form-item>
            </a-form>
          </div>
        </div>
      </Popup>
    )
  }
})